<template>
  <div class="dashboard-editor-container">
    <IndexCount />
    <div class="card-container mb-2">
      <div>流量收发(字节)</div>
      <Row :gutter="10">
        <Col :span="12">
          <div class="card-col">
            <div class="bytes-content">
              <div>已接收字节数</div>
              <CountTo
                class="bytes-num"
                :start-val="0"
                :end-val="bytesData['bytes.received'] || 0"
                :duration="1000"
              />
            </div>
          </div>
        </Col>
        <Col :span="12">
          <div class="card-col">
            <div class="bytes-content">
              <div>已发送字节数</div>
              <CountTo
                class="bytes-num"
                :start-val="0"
                :end-val="bytesData['bytes.sent'] || 0"
                :duration="1000"
              />
            </div>
          </div>
        </Col>
      </Row>
    </div>

    <div class="card-container">
      <Row>
        <Col :span="24" style="margin-bottom: 10px">
          <Select v-model:value="value" placeholder="请选择">
            <SelectOption
              v-for="item in options"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </SelectOption>
          </Select>
        </Col>
        <!-- 消息流入 -->
        <Col :xs="8" :sm="8" :lg="8">
          <div class="bartitle">
            <div
              class="divIcon"
              style="background-color: rgb(33, 143, 251)"
            ></div>
            消息流入
          </div>
          <LineChart
            seriesname="消息流入"
            :chartData="expectedData"
            :xAxisData="xAxisData"
            color="rgb(33,143,251, 1)"
            :lineColor="[
              { offset: 0, color: 'rgb(33,143,251, 0.8)' },
              { offset: 1, color: 'rgb(33,143,251, 0)' },
            ]"
          />
        </Col>
        <!-- 消息发出 -->
        <Col :xs="8" :sm="8" :lg="8">
          <div class="bartitle">
            <div
              class="divIcon"
              style="background-color: rgb(249, 141, 22)"
            ></div>
            消息发出
          </div>
          <LineChart
            seriesname="消息发出"
            :chartData="actualData"
            :xAxisData="xAxisData"
            color="rgb(249,141,22, 1)"
            :lineColor="[
              { offset: 0, color: 'rgb(249,141,22, 0.8)' },
              { offset: 1, color: 'rgb(249,141,22, 0)' },
            ]"
          />
        </Col>
        <!-- 消息丢弃 -->
        <Col :xs="8" :sm="8" :lg="8">
          <div class="bartitle">
            <div
              class="divIcon"
              style="background-color: rgb(247, 33, 51)"
            ></div>
            消息丢弃
          </div>
          <LineChart
            seriesname="消息丢弃"
            :chartData="droppedData"
            :xAxisData="xAxisData"
            color="rgb(247,33,51, 1)"
            :lineColor="[
              { offset: 0, color: 'rgb(247,33,51, 0.8)' },
              { offset: 1, color: 'rgb(247,33,51, 0)' },
            ]"
          />
        </Col>
        <!-- 连接数 -->
        <Col :xs="8" :sm="8" :lg="8">
          <div class="bartitle">
            <div
              class="divIcon"
              style="background-color: rgb(81, 195, 27)"
            ></div>
            连接数
          </div>
          <LineChart
            seriesname="连接数"
            :chartData="connectionsData"
            :xAxisData="xAxisData"
            color="rgb(81,195,27, 1)"
            :lineColor="[
              { offset: 0, color: 'rgb(81,195,27, 0.8)' },
              { offset: 1, color: 'rgb(81,195,27, 0)' },
            ]"
          />
        </Col>
        <!-- 主题数 -->
        <Col :xs="8" :sm="8" :lg="8">
          <div class="bartitle">
            <div
              class="divIcon"
              style="background-color: rgb(244, 219, 18)"
            ></div>
            主题数
          </div>
          <LineChart
            seriesname="主题数"
            :chartData="topicsData"
            :xAxisData="xAxisData"
            color="rgb(244,219,18, 1)"
            :lineColor="[
              { offset: 0, color: 'rgba(244,219,18,0.8)' },
              { offset: 1, color: 'rgba(244,219,18,0)' },
            ]"
          />
        </Col>
        <!-- 订阅数 -->
        <Col :xs="8" :sm="8" :lg="8">
          <div class="bartitle">
            <div
              class="divIcon"
              style="background-color: rgb(20, 198, 195)"
            ></div>
            订阅数
          </div>
          <LineChart
            seriesname="订阅数"
            :chartData="subscriptionsData"
            :xAxisData="xAxisData"
            color="rgb(20,198,195, 1)"
            :lineColor="[
              { offset: 0, color: 'rgb(20,198,195, 0.5)' },
              { offset: 1, color: 'rgb(20,198,195, 0)' },
            ]"
          />
        </Col>
      </Row>
    </div>
  </div>
</template>

<script setup>
import { onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
import { Card, Col, Row, Select, SelectOption } from 'ant-design-vue';
import { CountTo } from 'vue3-count-to';
import { getBytes, getServiceStatistics } from '@/api/server';
import IndexCount from './IndexCount.vue';
import LineChart from './LineChart.vue';

// 响应式数据声明
const value = ref('3600');
const options = ref([
  { label: '过去 1 小时', value: '3600' },
  { label: '过去 6 小时', value: '21600' },
  { label: '过去 12 小时', value: '43200' },
  { label: '过去 1 天', value: '86400' },
]);
const expectedData = ref([]);
const actualData = ref([]);
const droppedData = ref([]);
const connectionsData = ref([]);
const topicsData = ref([]);
const subscriptionsData = ref([]);
const xAxisData = ref([]);

const bytesData = reactive({});

// 定时器句柄
let timer = null;

// 查询统计数据（速率数据）
function querSulv() {
  getServiceStatistics(value.value).then((response) => {
    const xAxis = [];
    const expected = [];
    const actual = [];
    const dropped = [];
    const connections = [];
    const topics = [];
    const subscriptions = [];
    response.data.forEach((element) => {
      xAxis.push(formatTime(element.time_stamp));
      expected.push(element.received); // 消息流入
      actual.push(element.sent); // 消息发出
      dropped.push(element.dropped); // 消息丢弃
      connections.push(element.connections); // 连接数
      topics.push(element.topics); // 主题数
      subscriptions.push(element.subscriptions); // 订阅数
    });
    xAxisData.value = xAxis;
    expectedData.value = expected;
    actualData.value = actual;
    droppedData.value = dropped;
    connectionsData.value = connections;
    topicsData.value = topics;
    subscriptionsData.value = subscriptions;
  });
}

// 查询字节数数据
async function getBytesData() {
  const res = await getBytes();
  if (res.code === 200) {
    Object.assign(bytesData, res.data);
  }
}

// 格式化时间（hh:mm 格式）
function formatTime(time) {
  const date = new Date(time);
  const hour = date.getHours();
  const minutes = date.getMinutes();
  return `${hour < 10 ? `0${hour}` : hour}:${minutes < 10 ? `0${minutes}` : minutes}`;
}

// 监听 value 变化，重新查询速率数据
watch(value, () => {
  querSulv();
});

// 生命周期：组件挂载后调用数据接口并启动定时器
onMounted(() => {
  querSulv();
  getBytesData();
  timer = setInterval(() => {
    querSulv();
    getBytesData();
  }, 2000);
});

// 卸载前清除定时器
onBeforeUnmount(() => {
  clearInterval(timer);
});
</script>

<style lang="scss" scoped>
.dashboard-editor-container {
  padding-left: 20px;
}
.card-col {
  display: flex;
  align-items: center;
  .bytes-content {
    margin-left: 20px;
    > div {
      line-height: 30px;
    }
  }
  .bytes-num {
    font-size: 30px;
    font-weight: bold;
    color: #fff;
  }
}
</style>
